//! 行政区划代码相关.

use std::{
    collections::HashMap,
    fs,
    io::{self, BufRead},
};

/// 从代码字符串处理出固定长度的数组.
/// 转换后是 **数字的char的对应数字值** !
pub fn trans_number_str(number: &str) -> [u8; 6] {
    let mut number_arr: [u8; 6] = [0u8; 6];
    number_arr[..6].copy_from_slice(&number.as_bytes()[..6]);
    number_arr
}

/// 从代码`u8`串处理出固定长度的数组.
/// 转换后是 **数字的char的对应数字值** !
pub fn trans_number_u8(number: &[u8]) -> [u8; 6] {
    let mut number_arr: [u8; 6] = [0u8; 6];
    number_arr[..6].copy_from_slice(&number[..6]);
    number_arr
}

/// 读取行政区划代码表.
fn read_number_map_from_file(file_path: &str) -> HashMap<[u8; 6], String> {
    let file = fs::File::open(file_path).unwrap();
    let reader = io::BufReader::new(file);

    let mut result = HashMap::new();
    for line in reader.lines() {
        let line = line.unwrap();
        let parts: Vec<&str> = line.split_whitespace().collect();

        if parts.len() != 2 {
            continue;
        }

        let key = trans_number_str(parts[0]);
        let value = parts[1].to_string();
        result.insert(key, value);
    }

    result
}

pub struct AreaNumberManager {
    number_map: HashMap<[u8; 6], String>,
}

impl AreaNumberManager {
    /// 从表新建.
    pub fn with_map(number_map: HashMap<[u8; 6], String>) -> Self {
        Self { number_map }
    }

    /// 从文件新建.
    pub fn with_file(file_path: &str) -> Self {
        let number_map = read_number_map_from_file(file_path);
        Self::with_map(number_map)
    }

    /// 从代码得到地区名.
    ///
    /// 当级代码为00时必然不需要填写.
    /// 除三个特别行政区只要填最高级以外, 其他目前都需要填三级, 其中第二级可能是特殊名称.
    pub fn get_area(&self, mut number: [u8; 6]) -> Vec<&str> {
        let mut area_list = Vec::new();

        // 区县
        if number[4] != '0' as u8 || number[5] != '0' as u8 {
            if let Some(area) = self.number_map.get(&number) {
                area_list.push(area.as_str());
            }
        }

        // 市
        number[4] = '0' as u8;
        number[5] = '0' as u8;
        if number[2] != '0' as u8 || number[3] != '0' as u8 {
            if let Some(area) = self.number_map.get(&number) {
                area_list.push(area.as_str());
            } else if number[2] == '9' as u8 && number[3] == '0' as u8 {
                // 90 代表省（自治区）直辖县
                assert!(!area_list.is_empty());
                area_list.push("省（自治区）直辖县");
            } else if !area_list.is_empty() {
                // 没有第二级的市辖区
                area_list.push("市辖区");
            }
        }

        // 省
        number[2] = '0' as u8;
        number[3] = '0' as u8;
        if let Some(area) = self.number_map.get(&number) {
            area_list.push(area.as_str());
        }

        area_list.reverse();
        area_list
    }
}

// mod tests {
//     use super::*;

//     #[test]
//     fn test_number_to_area() {
//         let manager = AreaNumberManager::with_file("area_number.txt");
//         assert_eq!(
//             manager.get_area(trans_number_str("420111")),
//             vec!["湖北省", "武汉市", "洪山区"]
//         );
//         assert_eq!(
//             manager.get_area(trans_number_str("110102")),
//             vec!["北京市", "市辖区", "西城区"]
//         );
//         assert_eq!(
//             manager.get_area(trans_number_str("659005")),
//             vec!["新疆维吾尔自治区", "省（自治区）直辖县", "北屯市"]
//         );
//         assert_eq!(
//             manager.get_area(trans_number_str("810000")),
//             vec!["香港特别行政区"]
//         );
//     }
// }
